/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package database.actions;

import database.models.Tasks;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author Student
 */
public class DatabaseOperations {

    public static void saveRecords(Object object) {
        SessionFactory sessionFactory = HibernateConnectionSession.getSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        session.save(object);
        transaction.commit();
        session.close();


    }

    public static void updateRecord(Object object) {
        SessionFactory sessionFactory = HibernateConnectionSession.getSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        session.update(object);
        transaction.commit();
        session.close();
    }

    public static void deleteTask(String title) {
        SessionFactory sessionFactory = HibernateConnectionSession.getSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        SQLQuery query = session.createSQLQuery("delete from tasks where title='" + title + "'");
        query.executeUpdate();
        transaction.commit();
        session.close();
    }

    public static Object[] getRecords(String tableName) {

        SessionFactory sessionFactory = HibernateConnectionSession.getSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Query query = session.createQuery("from " + tableName);
        List list = query.list();
        Object[] objectArray = list.toArray();
        session.close();
        return objectArray;
    }

    public static Tasks getTaskRecord(String title) {
        Session hibernateSession = HibernateConnectionSession.getSessionFactory().openSession();
        Query querry = hibernateSession.createQuery("from Tasks tasks where tasks.title='" + title + "'");
        List list = querry.list();
        hibernateSession.close();
        return (Tasks) list.get(0);
    }
}
